import axios from 'axios'
import qs from 'qs'
import type { BaseResult } from './BaseResult'

const BASE_URL = 'https://i.huhuiyu.top'
const TOKEN_KEY = `${BASE_URL}_token`

class TokenInfo {
  static save(data: BaseResult) {
    if (data && data.token) {
      localStorage.setItem(TOKEN_KEY, data.token)
    }
  }

  static load(): string {
    const token = localStorage.getItem(TOKEN_KEY)
    return token ? token : ''
  }

  static clear() {
    localStorage.removeItem(TOKEN_KEY)
  }
}

class Api {
  static editorUrl(): string {
    return `${BASE_URL}/tools/editor/uploadimg`
  }

  static editorImageUrl(fid: string): string {
    return `${BASE_URL}/tools/editor/${fid}`
  }
  static userlogo(id: number): string {
    return `${BASE_URL}/user/info/logo/${id}?ts=${Date.now()}`
  }

  static send<T, R extends BaseResult>(
    url: string,
    param: T,
    cb: (data: R) => void,
    method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH',
  ) {
    url = BASE_URL + url
    if (method === 'GET') {
      url += '?' + qs.stringify(param)
      param = {} as T
    }
    const promise = axios({
      url,
      method,
      data: param,
      headers: {
        Authorization: TokenInfo.load(),
      },
    })

    promise
      .then((resp) => {
        const data = resp.data as BaseResult
        TokenInfo.save(data)
        cb(data as R)
      })
      .catch((err) => {
        console.error(err)
        cb({
          code: 500,
          success: false,
          message: '网络异常',
          token: '',
        } as R)
      })
  }

  static get<T, R extends BaseResult>(url: string, param: T, cb: (data: R) => void) {
    Api.send(url, param, cb, 'GET')
  }

  static post<T, R extends BaseResult>(url: string, param: T, cb: (data: R) => void) {
    Api.send(url, param, cb, 'POST')
  }

  static put<T, R extends BaseResult>(url: string, param: T, cb: (data: R) => void) {
    Api.send(url, param, cb, 'PUT')
  }

  static delete<T, R extends BaseResult>(url: string, param: T, cb: (data: R) => void) {
    Api.send(url, param, cb, 'DELETE')
  }

  static patch<T, R extends BaseResult>(url: string, param: T, cb: (data: R) => void) {
    Api.send(url, param, cb, 'PATCH')
  }
}

export { Api }
